from rest_framework.permissions import BasePermission
from django.core.cache import cache


class MyPermissions(BasePermission):
    method_dict = {
        1: "GET",
        2: "POST",
        3: "DELETE",
        4: "PUT",
        5: "PATCH",
    }

    def has_permission(self, request, view):
        user = request.user
        menu_list = cache.get(f"{user.id}_menus")
        pk = view.kwargs.get("pk")
        path = request.path.replace(pk, "{pk}") if pk else request.path
        for menu in menu_list:
            method = self.method_dict[menu.method] if menu.method else None
            if method == request.method and menu.api_path == path:
                return True
        return False
